package com.geekbang.perfma4j;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;

/**
 * Http采样监听器
 */
public class HttpSamplerListener
{
    private CountDownLatch countDownLatch;

    public HttpSamplerListener(CountDownLatch countDownLatch)
    {
        this.countDownLatch = countDownLatch;
    }

    /**
     * 采样清单，多个线程访问，保证线程安全
     */
    private List<HttpSampleResult> results = new CopyOnWriteArrayList<>();

    public void addSamplerResult(HttpSampleResult result)
    {
        results.add(result);
    }

    public void sampleEnd()
    {
        countDownLatch.countDown();
    }

    public void printReport()
    {
        long sum = 0;
        int avgRt;
        int p95Rt;
        long success = 0;
        long fail = 0;
        Collections.sort(results);
        for (HttpSampleResult result : results)
        {
            sum += result.getResponseTime();
            if (result.isSuccess())
            {
                success++;
            } else
            {
                fail++;
            }
        }
        avgRt = (int) (sum / results.size());
        p95Rt = results.get((int) (results.size() * 0.95)).getResponseTime();
        System.out.println("平均响应\t%95响应\t成功数\t失败数");
        System.out.println(avgRt + "\t" + p95Rt + "\t" + success + "\t" + fail);
    }
}
